package com.quanyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.encrypt.Coder;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.common.utils.*;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbUserMapper;
import com.quanyan.user.mapper.UserInfoMapper;
import com.quanyan.user.model.db.TbLevel;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.db.TbUserExample;
import com.quanyan.user.model.db.TbUserExt;
import com.quanyan.user.model.vo.request.ReqUserSetting;
import com.quanyan.user.model.vo.response.RespShareUrl;
import com.quanyan.user.model.vo.response.RespUserBaseInfo;
import com.quanyan.user.model.vo.response.RespUserSetting;
import com.quanyan.user.request.ReqAppUserLogin;
import com.quanyan.user.request.ReqBackstageUser;
import com.quanyan.user.request.ReqUserParam;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.service.*;
import com.quanyan.user.utils.LarkCodeUtil;
import com.quanyan.user.utils.ValidUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by jian.zhou on 2016/6/12.
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private static final Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private MyRedisTemplate myRedisTemplate;
    @Autowired
    private UserExtService userExtService;
    @Autowired
    private LevelService levelService;
    @Autowired
    private UserSmsService userSmsService;

    @Value("${quanyan_base_url}")
    private String quanyanBaseUrl;
    //客户端下载地址
    @Value("${client_url}")
    private String clientUrl;
    //用户默认头像地址
    @Value("${user_default_icon}")
    private String userDefaultIcon;
    @Autowired
    private HttpClientService httpClientService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserQueryService userQueryService;

    @Override
    public APIResponse<RespUserInfoBase> queryUserInfo(Integer userId) {
        logger.info("开始查询用户:{}的基本信息", userId);

        TbUser tbUser = this.getUser(userId);
        if (tbUser == null){
            logger.info("用户未注册，未查到信息");
            return APIResponse.returnFail("该用户不存在");
        }

        RespUserInfoBase respUserInfoBase = this.covertRespUserInfoBase(tbUser);
        return APIResponse.returnSuccess(respUserInfoBase);
    }


    @Override
    public APIResponse<RespUserInfoBase> queryUserInfo(String phone) {
        logger.info("start queryUserInfo param is :{} ", phone);
        if (StringUtils.isBlank(phone))
            return APIResponse.returnFail("phone is not null  ！");
        RedisKey mobileKey = new RedisKey(UserConstants.FAMILY_MOBILE, phone);
        Integer userId = (Integer) myRedisTemplate.get(mobileKey);
        logger.info("start get redis mobileKey:{} userId is :{}", mobileKey, userId);
        if (userId != null)
            return this.queryUserInfo(userId);

        TbUser tbUser = this.getUser(phone);
        if (tbUser == null)
            return APIResponse.returnFail("用户未注册");

        RespUserInfoBase respUserInfoBase = this.covertRespUserInfoBase(tbUser);
        logger.info("end queryUserInfo:{}", respUserInfoBase.toString());
        return APIResponse.returnSuccess(respUserInfoBase);
    }


    @Override
    public APIResponse<RespUserInfoBase> queryUserInfoByToken(String token) {
        logger.info("start queryUserInfo param is : ", token);
        if (StringUtils.isBlank(token))
            return APIResponse.returnFail("token is not null  ！");
        Integer userId = this.getUserIdByToken(token);
        return this.queryUserInfo(userId);

    }


    public APIResponse<RespUserInfoBase> queryUserInfoByWxOpenId(String wxOpenId) {
        if (StringUtil.isBlankOrNull(wxOpenId))
            return APIResponse.returnFail("token is not null  ！");

        logger.info("start queryUserInfo param is : ", wxOpenId);
        RedisKey wxKey = new RedisKey(UserConstants.FAMILY_WX_OPENID, wxOpenId);//微信openId与uid的映射
        Integer userId = (Integer) myRedisTemplate.get(wxKey);
        if (userId != null) //找到缓存信息
            return this.queryUserInfo(userId);

        //未找到缓存信息
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andWeixinAppOpenidEqualTo(wxOpenId);
        List<TbUser> tbUserList = tbUserMapper.selectByExample(example);
        if (tbUserList == null || tbUserList.size() == 0)
            return APIResponse.returnFail("未找到用户信息");

        TbUser tbUser = tbUserList.get(0);
        myRedisTemplate.set(wxKey, tbUser.getId()); // add缓存（uid和wx的关系映射）
        myRedisTemplate.hset(UserConstants.UID_MAP, tbUser.getId().toString(), tbUser);//add缓存

        RespUserInfoBase respUserInfoBase = this.covertRespUserInfoBase(tbUser);
        logger.info("end queryUserInfo:{}", respUserInfoBase.toString());
        return APIResponse.returnSuccess(respUserInfoBase);
    }


    @Override
    public APIResponse updateUserInfo(ReqUserParam reqUserParam) {
        if (reqUserParam == null)
            return APIResponse.returnFail("reqUserParam is not null");

        if (reqUserParam.getUid() == null)
            return APIResponse.returnFail("uid is not null");
        logger.info("start update user info param is :{}", reqUserParam);
        Integer uid = reqUserParam.getUid();
        TbUser tbUser = new TbUser();
        tbUser.setId(uid);
        tbUser.setNickName(reqUserParam.getNickName());
        tbUser.setBirthday(reqUserParam.getBorn());
        tbUser.setAreaId(reqUserParam.getAreaId());
        tbUser.setProvinceId(reqUserParam.getProvinceId());
        tbUser.setIcon(reqUserParam.getIcon());
        if(null != reqUserParam.getGender()){
            tbUser.setGender(reqUserParam.getGender().byteValue());
        }
        tbUser.setSign(reqUserParam.getSing());
        tbUser.setName(reqUserParam.getName());
        try {
            String userKey = UserConstants.getUserRedisKey(uid);
            tbUserMapper.updateByPrimaryKeySelective(tbUser);
            myRedisTemplate.set(userKey,tbUserMapper.selectByPrimaryKey(uid),7);
            String keyDetail = UserConstants.getUserDetailRedisKey(uid);
            myRedisTemplate.set(keyDetail,userInfoMapper.findUserInfoDetail(uid),7);
            httpClientService.updateSetting(uid,null,1,1);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("", e);
            return APIResponse.returnFail("系统异常！");
        }

    }


    @Override
    public APIResponse<List<RespUserInfoBase>> batchQueryUserInfo(List<Integer> lstUserId) {
        if (lstUserId == null || lstUserId.size() < 1)
            return APIResponse.returnFail("参数不能为空！");

        logger.info("start batch query user info param is : {},num;{}", lstUserId, lstUserId.size());
        try {
            List<TbUser> tbUserList = this.queryUserInfoByList(lstUserId);
            Map<Integer,TbUserExt> mapExt = userExtService.getExt(lstUserId);//批量查询拓展信息
            Map<Integer,TbLevel> mapLevel = levelService.batchTbUserLevel(lstUserId); //批量查询登记信息

            if (tbUserList == null || tbUserList.size() < 1)
                return APIResponse.returnSuccess(null);

            List<RespUserInfoBase> lst  = new ArrayList<RespUserInfoBase>();
            for (TbUser tbUser : tbUserList) {
                RespUserInfoBase respUserInfoBase = this.covertRespUserInfoBaseBatch(tbUser);
                TbUserExt tbUserExt = mapExt.get(tbUser.getId());
                if(tbUserExt != null){
                    respUserInfoBase.setWeight(tbUserExt.getWeight());
                    respUserInfoBase.setHeight(tbUserExt.getHeight());
                    respUserInfoBase.setNameVerifyStatus(tbUserExt.getNameVerifyStatus());
                }
                TbLevel tbLevel = mapLevel.get(tbUser.getId());
                if(tbLevel != null )
                    respUserInfoBase.setLevel(tbLevel.getLevel());
                lst.add(respUserInfoBase);
            }
            logger.info("end batch query user info result is : {} ", lst.toString());
            return APIResponse.returnSuccess(lst);
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }

    public Map<Integer,RespUserInfoBase> batchQueryUserInfoToMap(List<Integer> lstUserId){
        List<TbUser> tbUserList = this.queryUserInfoByList(lstUserId);
        Map<Integer,TbUserExt> mapExt = userExtService.getExt(lstUserId);//批量查询拓展信息
        Map<Integer,TbLevel> mapLevel = levelService.batchTbUserLevel(lstUserId); //批量查询登记信息
        if (tbUserList == null || tbUserList.size() < 1)
            return null;

        Map<Integer,RespUserInfoBase> map = new HashMap<>();
        for (TbUser tbUser: tbUserList){
            RespUserInfoBase respUserInfoBase = this.covertRespUserInfoBase(tbUser);
            TbUserExt tbUserExt = mapExt.get(tbUser.getId());
            if(tbUserExt != null){
                respUserInfoBase.setWeight(tbUserExt.getWeight());
                respUserInfoBase.setHeight(tbUserExt.getHeight());
                respUserInfoBase.setNameVerifyStatus(tbUserExt.getNameVerifyStatus());
            }
            TbLevel tbLevel = mapLevel.get(tbUser.getId());
            if(tbLevel != null )
                respUserInfoBase.setLevel(tbLevel.getLevel());

            map.put(respUserInfoBase.getUid(),respUserInfoBase);
        }
        return map;
    }

    /**
     * 获取用户二维码
     * @param uid
     * @return
     */
    @Override
    public String getUserQRCode(Integer uid) {
        TbUser user = this.getUser(uid);
        StringBuffer shortUrl = new StringBuffer();
        if(user != null){
            RespUserBaseInfo respUserBaseInfo = new RespUserBaseInfo();
            respUserBaseInfo.setNickName(user.getNickName());
            respUserBaseInfo.setUid(uid);
            if(null != user.getBirthday()){
                respUserBaseInfo.setBorn(user.getBirthday().getTime());
            }else{
                respUserBaseInfo.setBorn(0);
            }
            respUserBaseInfo.setGender(user.getGender());
            respUserBaseInfo.setIcon(user.getIcon());
            String json = GsonUtils.toJson(respUserBaseInfo);
            String param = Coder.urlEncoder(json.trim());

            StringBuffer sb = new StringBuffer();
            sb.append("http://").append(quanyanBaseUrl).append("?source=bailingniaoqrcode&param=").append(param).append("&type=info");
            String httpResult = ShortUrlUtils.getShortUrl(sb.toString());

            if(httpResult != null){
                List<RespShareUrl> respShareUrls = JSON.parseArray(httpResult, RespShareUrl.class);
                shortUrl.append(respShareUrls.get(0).getUrl_short()).append("?source=bailingniaoqrcode&d=").append(uid).append("&m=u");
            }
        }else{
            shortUrl.append("http://").append(quanyanBaseUrl);
        }
        return shortUrl.toString();
    }

    /**
     * 批量查询用户信息
     * @param lstUserId
     * @return
     */
    public List<TbUser> queryUserInfoByList(List<Integer> lstUserId){
        if (lstUserId == null || lstUserId.size() < 1)
            return null;
        logger.info("start batch query user info param is : {},num;{}", lstUserId, lstUserId.size());
        List<TbUser> tbUserList = new ArrayList<TbUser>();
        List<Integer> noRedisUid = new ArrayList<Integer>();//没在缓存中的UID
        for (Integer uid : lstUserId) {
            TbUser tbUser = (TbUser) myRedisTemplate.hget(UserConstants.UID_MAP, uid.toString());
            if (tbUser != null)//在缓存中有
                tbUserList.add(tbUser);
            else
                noRedisUid.add(uid);
        }
        logger.info("redis tbUserList num:{},no redis uid num :{}", tbUserList.size(), noRedisUid.size());
        if (noRedisUid.size() > 0) { //从数据库中读取没在缓存中的用户信息
            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria c = example.createCriteria();
            c.andIdIn(noRedisUid);
            List<TbUser> lstUser = tbUserMapper.selectByExample(example);
            if (lstUser != null && lstUser.size() > 0) {
                logger.info("db user num : {}", lstUser.size());
                for (TbUser tbUser : lstUser) {
                    myRedisTemplate.hset(UserConstants.UID_MAP, tbUser.getId().toString(), tbUser);
                }
                tbUserList.addAll(lstUser);
            }
        }
        return tbUserList;
    }


    @Override
    public APIResponse<RespUserInfoBase> appLogin(ReqAppUserLogin reqAppUserLogin) {
        logger.info("star app user login");
        if (reqAppUserLogin == null)
            return APIResponse.returnFail("参数不能为空！");

        if (reqAppUserLogin.getType() == null)
            return APIResponse.returnFail("type不能为空！");

        logger.info("star app user login param is ; {}", reqAppUserLogin.toString());
        String token = UUIDUtils.getUUID();
        if (reqAppUserLogin.getType().byteValue() == Constants.LoginType.VALID_CODE){ //验证码方式登录
            if ("".equals(reqAppUserLogin.getMobile()))
                return APIResponse.returnFail("mobile不能为空！");

            logger.info("star valid validCode");
//            boolean flag = smsService.verifyValidCode(reqAppUserLogin.getMobile(), SmsApi.MESSAGE_TEMPLATE_USER_REGISTER, reqAppUserLogin.getValidCode());
            APIResponse responseOne = userSmsService.checkCode(reqAppUserLogin.getValidCode(),reqAppUserLogin.getMobile());
            boolean flag = responseOne.isRet();
            int errcode = responseOne.getErrcode();
            if (flag && errcode != 200) {
                return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
            }
            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria criteria = example.createCriteria();
            criteria.andMobileEqualTo(reqAppUserLogin.getMobile());
            int count = tbUserMapper.countByExample(example);
            if (count > 0) {//已注册
                logger.info("已经注册");
                APIResponse<RespUserInfoBase> response = this.queryUserInfo(reqAppUserLogin.getMobile());
                if (response.getData() != null){
                    AppUserCacheInfo appUserCacheInfo = new AppUserCacheInfo();
                    appUserCacheInfo.setUser_id(response.getData().getUid());
                    appUserCacheInfo.setCreate_time(DateUtils.getSecondTimestampOne(new Date()));
                    appUserCacheInfo.setDev(3);
                    String userInfo = JSON.toJSONString(appUserCacheInfo);
                    myRedisTemplate.setCLogin(token, userInfo, Constants.TOKEN_EXPIRED_TIME);
                    response.getData().setToken(token);
                }
                return response;
            } else { //未注册

                logger.info("未注册,开始注册用户信息");
                TbUser tbUser = new TbUser();
                tbUser.setMobile(reqAppUserLogin.getMobile().replaceAll(" ",""));
                if(!ValidUtils.isRegMobile(tbUser.getMobile())){
                    logger.info("手机号不符合规则！");
                    return APIResponse.returnFail("手机号不符合规则！");
                }
                tbUser.setNickName(LarkCodeUtil.generateDefaultNickName(reqAppUserLogin.getMobile()));
                tbUser.setIsPhoto(false);
                tbUser.setGender((byte)0);
                tbUser.setSourceChannel(Constants.SourceChannel.WECHAT);
                tbUser.setUserSetting(JSONObject.toJSONString(new ReqUserSetting()));//初始化用户设置
                tbUser.setIsEnable((byte)1);
                tbUser.setCreateTime(new Date());
                tbUserMapper.insertSelective(tbUser);
                tbUser.setLarkCode(LarkCodeUtil.generateLarkCode(tbUser.getId()));
                tbUserMapper.updateByPrimaryKeySelective(tbUser);
                logger.info("未注册,end注册用户信息");
                APIResponse<RespUserInfoBase> response = this.queryUserInfo(reqAppUserLogin.getMobile());
                if (response.getData() != null){
                    AppUserCacheInfo appUserCacheInfo = new AppUserCacheInfo();
                    appUserCacheInfo.setUser_id(response.getData().getUid());
                    appUserCacheInfo.setCreate_time(DateUtils.getSecondTimestampOne(new Date()));
                    appUserCacheInfo.setDev(3);
                    String userInfo = JSON.toJSONString(appUserCacheInfo);
                    myRedisTemplate.setCLogin(token, userInfo, Constants.TOKEN_EXPIRED_TIME);
                    response.getData().setToken(token);
                }

                return response;
            }
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public RespUserSetting getUserSetting(Integer userId) {
        logger.info("start query user setting uid: {}", userId);
        RespUserSetting respUserSetting = new RespUserSetting();
        if (userId != null) {
            TbUser tbUser = tbUserMapper.selectByPrimaryKey(userId);
            if (tbUser != null) {
                if (StringUtils.isNotBlank(tbUser.getUserSetting())){
                    respUserSetting = JSONObject.parseObject(tbUser.getUserSetting(), RespUserSetting.class);
                    if(tbUser.getUserSetting().length() < JSONObject.toJSONString( new RespUserSetting()).length())
                        this.updateSetting(respUserSetting,userId);
                }
                else {
                  this.updateSetting(respUserSetting,userId);

                } // 未设置 ，设置为默认设置
            }
        }
        logger.info("end query user setting result: {}", respUserSetting.toString());
        return respUserSetting;
    }

    public void updateSetting(RespUserSetting respUserSetting ,Integer userId){
        TbUser t = new TbUser();
        t.setId(userId);
        t.setUserSetting(JSONObject.toJSONString(respUserSetting));
        tbUserMapper.updateByPrimaryKeySelective(t);
        String userKey = UserConstants.getUserRedisKey(userId);
        myRedisTemplate.set(userKey,tbUserMapper.selectByPrimaryKey(userId),7);
    }

    @Override
    public void updateUserSetting(Integer userId, ReqUserSetting reqUserSetting) {
        logger.info("start update user setting uid: {},param:{}", userId, reqUserSetting.toString());
        if (userId != null) {
            TbUser tbUser = userQueryService.getUser(userId);
            ReqUserSetting reqUserSettingOld = JSONObject.parseObject(tbUser.getUserSetting(), ReqUserSetting.class);
            reqUserSetting.getUpReqUserSetting(reqUserSettingOld);
            TbUser t = new TbUser();
            t.setId(userId);
            t.setUserSetting(JSONObject.toJSONString(reqUserSettingOld));
            tbUserMapper.updateByPrimaryKeySelective(t);
            String userKey = UserConstants.getUserRedisKey(userId);
            myRedisTemplate.set(userKey, tbUserMapper.selectByPrimaryKey(userId), 7);
            httpClientService.updateSetting(userId,null,1,1);
        }
        logger.info("end update user setting");
    }

    @Override
    public Boolean isBindingMobile(Integer uid) {
        if (uid != null) {
            TbUser tbUser = this.getUser(uid);
            if (tbUser != null) {
                //已经绑定
                //未绑定
                return "".equals(tbUser.getMobile());
            }

        }
        return false;//未绑定

    }

    /**
     * 获取userID用户信息
     */
    public TbUser getUser(Integer uid) {
        if(uid == null)
            return null;
        String uidStr = uid.toString();
        StringBuffer sb = new StringBuffer();
        sb.append(UserConstants.C).append(uidStr);
        TbUser tbUser = (TbUser) myRedisTemplate.get(sb.toString());//查询缓存中的用户信息
        if (tbUser == null) { //判断redis是否缓存
            tbUser = tbUserMapper.selectByPrimaryKey(uid);
            if (tbUser == null)//未注册
                return null;
            myRedisTemplate.hset(UserConstants.UID_MAP, uidStr, tbUser); //缓存用户信息

            //缓存用户信息并设置过期日期
            myRedisTemplate.set(sb.toString(),tbUser,7);

            RedisKey mobileKey = new RedisKey(UserConstants.FAMILY_MOBILE, tbUser.getMobile());//缓存手机号与uid的映射
            myRedisTemplate.set(mobileKey, uid);

            RedisKey wxKey = new RedisKey(UserConstants.FAMILY_WX_OPENID, tbUser.getWeixinAppOpenid());//缓存微信openId与uid的映射
            myRedisTemplate.set(wxKey, uid);
        }
        //为用户添加默认头像
        if (StringUtil.isBlankOrNull( tbUser.getIcon() )) {
            tbUser.setIcon(userDefaultIcon);
        }
        return tbUser;
    }


    /**
     * 根据手机号获取userId
     */
    public TbUser getUser(String phone) {
        TbUser tbUser = null;
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andMobileEqualTo(phone);
        List<TbUser> tbUserList = tbUserMapper.selectByExample(example);
        if (tbUserList != null && tbUserList.size() > 0) {
            RedisKey mobileKey = new RedisKey(UserConstants.FAMILY_MOBILE, phone);//手机号与userId的映射缓存
            tbUser = tbUserList.get(0);
            myRedisTemplate.set(mobileKey, tbUser.getId());
            myRedisTemplate.hset(UserConstants.UID_MAP, tbUser.getId().toString(), tbUser);
        }
        return tbUser;
    }

    /**
     * 转换返回用户信息
     */
    public RespUserInfoBase covertRespUserInfoBase(TbUser tbUser) {
        RespUserInfoBase respUserInfoBase = new RespUserInfoBase();
        respUserInfoBase.setUid(tbUser.getId());
        respUserInfoBase.setGender(tbUser.getGender().intValue());
        respUserInfoBase.setNickName(tbUser.getNickName());
        respUserInfoBase.setIcon(tbUser.getIcon());
        respUserInfoBase.setRealName(tbUser.getName());
        respUserInfoBase.setMobile(tbUser.getMobile());
        respUserInfoBase.setIsDaren(tbUser.getIsMaster());
        if(tbUser.getYear() != null)
           respUserInfoBase.setAge(this.getCurrentAge(tbUser.getYear().intValue()));
        respUserInfoBase.setAccount(tbUser.getAccount());
        respUserInfoBase.setAreaId(tbUser.getAreaId());
        respUserInfoBase.setProvinceId(tbUser.getProvinceId());

        TbUserExt tbUserExt = userExtService.getTbUserExt(tbUser.getId()); // 拓展信息
        if(tbUserExt != null){
            respUserInfoBase.setWeight(tbUserExt.getWeight());
            respUserInfoBase.setHeight(tbUserExt.getHeight());
            respUserInfoBase.setNameVerifyStatus(tbUserExt.getNameVerifyStatus());
        }

        TbLevel tbLevel = levelService.getTbUserLevel(tbUser.getId()); // 等级信息
        if(tbLevel != null )
            respUserInfoBase.setLevel(tbLevel.getLevel());

        return respUserInfoBase;
    }

    /**
     * 转换返回用户信息
     */
    public RespUserInfoBase covertRespUserInfoBaseBatch(TbUser tbUser) {
        if (tbUser == null)
            return null;
        RespUserInfoBase respUserInfoBase = new RespUserInfoBase();
        respUserInfoBase.setUid(tbUser.getId());
        respUserInfoBase.setGender(tbUser.getGender().intValue());
        respUserInfoBase.setNickName(tbUser.getNickName());
        respUserInfoBase.setIcon(tbUser.getIcon());
        respUserInfoBase.setRealName(tbUser.getName());
        respUserInfoBase.setMobile(tbUser.getMobile());
        if(tbUser.getYear() != null)
            respUserInfoBase.setAge(this.getCurrentAge(tbUser.getYear().intValue()));
        respUserInfoBase.setAccount(tbUser.getAccount());
        respUserInfoBase.setAreaId(tbUser.getAreaId());
        respUserInfoBase.setProvinceId(tbUser.getProvinceId());
        return respUserInfoBase;
    }

    /**
     * 根据token值获取用户id  C++
     */
    public Integer getUserIdByToken(String token) {
        if(token == null)
            return null;
        logger.info("根据token获取UID:---------------------->{}",token);
        RedisKey redisKey = new RedisKey(RedisConstants.C_FAMILY_KEY, token);
        try {
            if (null != redisKey.getRedisKey() && redisKey.getRedisKey().length() > 0) {
                AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo) myRedisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
                if (null != appUserCacheInfo && null != appUserCacheInfo.getUser_id())
                    return appUserCacheInfo.getUser_id();
            }
        } catch (UnsupportedEncodingException e) {
            logger.info("{}",e);
        }
        return null;
    }

    /**
     * 获取年龄
     */
    public int getCurrentAge(int year) {
        if (year == 0)
            return 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        Integer currentYear = Integer.parseInt(sdf.format(date));
        return currentYear - year;
    }


    @Override
    public List<Integer> queryUidByNickName(String nickName){
        List<Integer> lstUid = null;
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andNickNameEqualTo(nickName);
        List<TbUser> lst = tbUserMapper.selectByExample(example);
        if (lst != null && lst.size() > 0){
            lstUid = new ArrayList<>();
            for (TbUser u:lst){
                lstUid.add(u.getId());
            }
        }
        return lstUid;
    }


    @Override
    public APIResponse registerMemberUser(ReqBackstageUser reqBackstageUser){
        String phone = reqBackstageUser.getMobile();
        List<String> mobiles = new ArrayList<>();
        mobiles.add(phone);
        List<String> params = new ArrayList<>();
        TbUser tbUser = this.getUser(phone);
        if(tbUser != null){//已经注册
            logger.info("该用户已经注册！{}",tbUser.getId());

            params.add(tbUser.getNickName());
            params.add(reqBackstageUser.getMemberCardName());
            params.add(clientUrl);
            userSmsService.sendSms(mobiles,3,3,params);
            return APIResponse.returnSuccess(tbUser.getId());
        }else {
            logger.info("未注册,开始注册用户信息");
            tbUser = new TbUser();
//            String mobile = reqBackstageUser.getMobile();
            if (phone != null) {
                tbUser.setMobile(phone.replaceAll(" ",""));
            }

            if(!ValidUtils.isRegMobile(phone)){
                logger.info("手机号不符合规则！");
                return APIResponse.returnFail("手机号不符合规则！");
            }
            tbUser.setIsPhoto(false);
            tbUser.setGender((byte)0);
            if(reqBackstageUser.getMemberName()!=null)
                tbUser.setNickName(reqBackstageUser.getMemberName());
            else
                tbUser.setNickName(LarkCodeUtil.generateDefaultNickName(phone));
            tbUser.setSourceChannel(Constants.SourceChannel.BACKSTAGE);
            tbUser.setUserSetting(JSONObject.toJSONString(new RespUserSetting()));//初始化用户设置
            String pwd = RandomStringGenerator.getRandomDigitByLength(6);
            tbUser.setPassword(DataEncryptionUtils.SHA1(pwd).toUpperCase());
            tbUser.setRegTime(new Date());
            tbUser.setIsEnable((byte)1);
            tbUser.setCreateTime(new Date());
            tbUserMapper.insertSelective(tbUser);
            tbUser.setLarkCode(LarkCodeUtil.generateLarkCode(tbUser.getId()));
            tbUserMapper.updateByPrimaryKeySelective(tbUser);
            params.add(reqBackstageUser.getMemberName());
            params.add(reqBackstageUser.getMemberCardName());
            params.add(clientUrl);
            params.add(phone);
            params.add(pwd);
            userSmsService.sendSms(mobiles,4,3,params);
            return APIResponse.returnSuccess(tbUser.getId());
        }

    }

    @Override
    public APIResponse registerClubUser(String mobile){
        mobile = StringUtil.replaceBlank(mobile);
        TbUser tbUser = this.getUser(mobile);
        if(tbUser != null )
            return APIResponse.returnSuccess(tbUser.getId());
        tbUser = new TbUser();
        if (mobile != null) {
            tbUser.setMobile(mobile);
        }

        if(!ValidUtils.isRegMobile(mobile)){
            logger.info("手机号不符合规则！");
            return APIResponse.returnFail("手机号不符合规则！");
        }

        tbUser.setIsPhoto(false);
        tbUser.setGender((byte)0);
        tbUser.setSourceChannel(Constants.SourceChannel.BACKSTAGE);
        tbUser.setUserSetting(JSONObject.toJSONString(new RespUserSetting()));//初始化用户设置
        String pwd = mobile.substring(mobile.length() - 6, mobile.length());
        tbUser.setPassword(DataEncryptionUtils.SHA1(pwd).toUpperCase());
        tbUser.setRegTime(new Date());
        tbUser.setIsEnable((byte)1);
        tbUser.setCreateTime(new Date());
        tbUserMapper.insertSelective(tbUser);
        tbUser.setLarkCode(LarkCodeUtil.generateLarkCode(tbUser.getId()));
        tbUserMapper.updateByPrimaryKeySelective(tbUser);
        return APIResponse.returnSuccess(tbUser.getId());
    }

    public APIResponse<Map<String,Integer>> batchRegisterMemberUser(List<ReqBackstageUser> reqBackstageUsers){
        if(reqBackstageUsers != null && reqBackstageUsers.size() > 0){
            Map<String,Integer> mobileId = new HashMap<>();

            List<String> lstPhone = new ArrayList<>();
            Map<String,String> map = new HashMap<>();
            for (ReqBackstageUser r : reqBackstageUsers){
                lstPhone.add(r.getMobile().replaceAll(" ", ""));
                map.put(r.getMobile().replaceAll(" ", ""),r.getMemberName());
            }

            TbUserExample example = new TbUserExample();
            TbUserExample.Criteria criteria = example.createCriteria();
            criteria.andMobileIn(lstPhone);
            List<TbUser> lstTbUser = tbUserMapper.selectByExample(example);

            for (TbUser tbUser : lstTbUser){
                mobileId.put(tbUser.getMobile(),tbUser.getId());
                if (map.containsKey(tbUser.getMobile()))
                    map.remove(tbUser.getMobile());
            }

            if(map.size() < 1)
                return APIResponse.returnSuccess(mobileId);

            List<TbUser> newTbUser = new ArrayList<>();
            for (Map.Entry<String,String> entry : map.entrySet()){
                String mobile = entry.getKey();
                TbUser tbUser = new TbUser();
                if (mobile != null) {
                    tbUser.setMobile(mobile.replaceAll(" ",""));
                    if(ValidUtils.isRegMobile(tbUser.getMobile()))
                        newTbUser.add(tbUser);
                    else
                        logger.info("手机号不符合规则！{}",mobile);
                }

                tbUser.setType((byte)1);
                tbUser.setNickName(LarkCodeUtil.generateDefaultNickName(mobile));
                tbUser.setIsPhoto(false);
                tbUser.setGender((byte)0);
                tbUser.setSourceChannel(Constants.SourceChannel.BACKSTAGE);
                tbUser.setUserSetting(JSONObject.toJSONString(new RespUserSetting()));//初始化用户设置
                String pwd = mobile.substring(mobile.length() - 6, mobile.length());
                tbUser.setPassword(DataEncryptionUtils.SHA1(pwd).toUpperCase());
                //tbUser.setRegType();
                tbUser.setLarkCode("");
                tbUser.setDeviceToken("");
                tbUser.setGetuiId("");
                tbUser.setRegTime(new Date());
                tbUser.setIsEnable((byte)1);
                tbUser.setCreateTime(new Date());

            }
            try {
                if(newTbUser != null && newTbUser.size() > 0){
                    userInfoMapper.batchInsert(newTbUser);
                    TbUserExample example1 = new TbUserExample();
                    TbUserExample.Criteria criteria1 = example1.createCriteria();
                    criteria1.andMobileIn(lstPhone);
                    List<TbUser> lstTbUser1 = tbUserMapper.selectByExample(example1);
                    updateUserLarkCode(lstTbUser1);
                    for (TbUser t : lstTbUser1){
                        mobileId.put(t.getMobile(),t.getId());
                    }
                }
            } catch (Exception e) {
                logger.error("{}",e);
                return APIResponse.returnFail("系统异常");
            }
            return APIResponse.returnSuccess(mobileId);

        }
        return APIResponse.returnFail("参数不能为空！");
    }

    /**
     * 更新用户百灵鸟号
     * @param list
     */
    @Async
    private void updateUserLarkCode(List<TbUser> list){
        logger.info("开始批量更改larkCODE");
        for(TbUser tbUser : list){
            tbUser.setLarkCode(LarkCodeUtil.generateLarkCode(tbUser.getId()));
        }
        userInfoMapper.updateLarkCode(list);
        logger.info("结束批量更改larkCODE");
    }

}
